import cv2

original_image = cv2.imread("pic/after.png")
image = original_image.copy()
image = cv2.GaussianBlur(image, (9,9),1,1)
cv2.imshow("image", image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 中值滤波平滑，消除噪声
# 当图片缩小后，中值滤波的孔径也要相应的缩小，否则会将有效的轮廓擦除
binary = cv2.medianBlur(gray,5)
#转换为二值图像
ret, binary = cv2.threshold(binary, 203, 255, cv2.THRESH_BINARY)
cv2.imshow("binary", binary)
#再次检测边缘
canny = cv2.Canny(binary, 1, 100, 3)
cv2.imshow("canny", canny)
#cv2.imwrite('pic/canny_screen3.png', canny)

h,w=canny.shape
print(h,w)
x=int(w/2)
y=int(h/2)
print(2*int(w/4))
print(2*int(h/4))
he=[]
we=[]
for i in range(h):
    if canny[i][x]==255:
        try:
            if canny[i-1][x]==0 and canny[i+1][x]==0:
                for long in range(-8,8):
                    if canny[i][x+long]!=255:
                        break
                    if long == 7:
                        he.append(i)
        except IndexError:
            continue
print(he)
for i in range(w):
    if canny[y][i]==255:
        try:
            if canny[y][i-1] == 0 and canny[y][i+1] == 0:
                for long in range(-8,8):
                    if canny[y+long][i]!=255:
                        break
                    if long==7:
                        we.append(i)
        except IndexError:
            continue
print(we)
cv2.rectangle(original_image, (we[0], he[0]), (we[-1],he[-1]), (36, 255, 12), 2)
cv2.namedWindow('detected',0)
cv2.resizeWindow('detected',w,h)
cv2.imshow("detected", original_image)
#cv2.imwrite('pic/detected_screen3.png', original_image)
cv2.waitKey(0)



